import React from 'react';
import { connect } from 'dva';
import { Link, browserHistory } from 'dva/router';
import { Table, Row, Col, Form, Input, Icon, InputNumber, Radio, DatePicker, Select, Upload, Button, Switch, Modal, Popconfirm, Tabs, message } from 'antd';
const R = require('ramda');
import moment from 'moment'
const dateFormat = 'YYYY-MM-DD';
const { RangePicker } = DatePicker;
import OperatorConstant from "../../../utils/OperatorConstant";
import InoviceDetail from '../../../components/drawback/InoviceDetail';
import RightBox from "../../../components/commons/RightBox";
import RIGHT from "../../../utils/RightConstants";




const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;

const recinvoices = Form.create()(class recinvoices extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            type: "2",
            selectedRowKeys: [],
            selectedRows: []
        }
    }

    componentDidMount() {
        this.props.dispatch({
            type: 'recinvoices/getRecinvoicesList',
        });
    }


    handleResetFields = () => {
        if (this.editCustomer) this.editCustomer.handleResetFields();
    }

    handleCancel = (flag) => {
        if (flag) {
            this.handleResetFields();
        }
    }

    onEdit = (record, type) => {
        this.handleOpen(record, type);
    }

    handleOpen = (record, isDisable) => {
        this.props.dispatch({ type: 'recinvoices/getInoviceheaderByOrderId', payload: { orderId: record.id } });
        this.props.dispatch({ type: 'recinvoices/getInoviceproductsByOrderId', payload: { orderId: record.id } });
        this.props.dispatch({ type: 'recinvoices/queryDrawerList', payload: { cstId: record.cstid } });
        this.inoviceDetail.handleOpen(isDisable, this.state.type);
    }

    batchCheckinvoice = () => {
        if (this.state.selectedRows.length === 0) { message.info("请至少选择一条记录"); return; }
        let flag = true;
        this.state.selectedRows.map(item => {
            if (item.openinvoicestatus !== '4') flag = false;
        })
        if (flag) {
            this.props.dispatch({
                type: 'recinvoices/batchCheckinvoice', payload: {
                    ids: this.state.selectedRowKeys,
                    onSuccess: () => {
                        this.handleSearch(true);
                    }
                }
            });
        } else {
            message.info("只能选择待验票的记录"); return;
        }
    }

    handleCheckedCancel = (record) => {
        this.props.dispatch({
            type: 'recinvoices/checkinvoice',
            payload: {
                orderId: record.id,
                checkStatus: '4',
                memo: '取消验票',
                onSuccess: () => {
                    this.handleSearch(true);
                }
            }
        });
    }

    handleSearch = (flag) => {
        let values = this.props.form.getFieldsValue();
        let newPage = this.props.recinvoices.page;
        newPage.page = flag ? newPage.page : 1;


        this.props.dispatch({
            type: 'recinvoices/getRecinvoicesList',
            payload: {
                contractno: values.contractno,
                status: values.status,
                page: newPage,
            }
        });
        this.setState({ type: values.status });


    };



    columns = [
        { title: '订单号', dataIndex: 'orderno', key: 'orderno' },

        { title: '合同协议号', dataIndex: 'contractno', key: 'contractno' },


        { title: '下单时间', dataIndex: 'orderTime', key: 'orderTime' },
        { title: '客户名称', dataIndex: 'companyname', key: 'companyname' },
        { title: '开票金额', dataIndex: 'draweramount', key: 'draweramount' },
        { title: '服务专员', dataIndex: 'waiterName', key: 'waiterName' },
        { title: '收票截止时间', dataIndex: 'deadline', key: 'deadline' },

        {
            title: '外汇状态', key: 'foxerstatus',
            render(record) {
                if (record.foxerstatus == 0) {
                    return "未收齐";
                } else if (record.foxerstatus == 1) {
                    return "已收齐";
                } else {
                    return "未知";
                }
            }
        },

        {
            title: '发票状态', key: 'openinvoicestatus',
            render(record) {
                if (record.openinvoicestatus == 0) {
                    return "未做开票资料";
                } else if (record.openinvoicestatus == 1) {
                    return "待做开票资料";
                } else if (record.openinvoicestatus == 2) {
                    return "待收票";
                } else if (record.openinvoicestatus == 3) {
                    return "待审核";
                } else if (record.openinvoicestatus == 4) {
                    return "待验票";
                } else if (record.openinvoicestatus == 5) {
                    return "已验票";
                } else {
                    return "未知";
                }
            }

        },
        { title: '验票时间', dataIndex: 'checkInvoicetime', key: 'checkInvoicetime' },
        { title: '报关金额', dataIndex: 'totleamount', key: 'totleamount' },
        {
            title: '预开票',
            render(record) {
                return record.isperopeninvoice === "2" ? "是" : "否";
            }
        },

        {
            title: '操作', key: 'key_oprator',

            render: (text, record, index) => {

                if (record.openinvoicestatus == 2) {
                    return (
                        <span>
                            <RightBox resource={RIGHT.DRAW.DRAW_INVOICE_REC} split={true}><a href="#" onClick={() => this.onEdit(record, OperatorConstant.add)}>收票</a></RightBox>
                            <a href="#" onClick={() => this.onEdit(record, OperatorConstant.view)}>查看</a>
                        </span>
                    );
                } else if (record.openinvoicestatus == 4) {
                    return (
                        <span>
                            <RightBox resource={RIGHT.DRAW.DRAW_INVOICE_CHECKIN} split={true}><a href="#" onClick={() => this.onEdit(record, OperatorConstant.drawer_checkinvoice)}>认证发票</a></RightBox>
                            <a href="#" onClick={() => this.onEdit(record, OperatorConstant.view)}>查看</a>
                        </span>

                    );
                } else if (record.openinvoicestatus == 5) {
                    return (
                        <span>
                            <RightBox resource={RIGHT.DRAW.DRAW_INVOICE_CHECKED_CANCEL} split={true}>
                                <Popconfirm onConfirm={this.handleCheckedCancel.bind(this, record)} okText="是" cancelText="否"
                                    placement="leftTop" title={'是否确认取消验票?'}>
                                    <a href="#">取消验票</a>
                                </Popconfirm></RightBox>
                            <a href="#" onClick={() => this.onEdit(record, OperatorConstant.view)}>查看</a>
                        </span>

                    );
                }
            }
        }
    ];

    rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => this.setState({ selectedRowKeys, selectedRows })
    };

    render() {
        let dataSouce = R.isNil(this.props.recinvoices.dataSource) ? {} : this.props.recinvoices.dataSource;
        let formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 18 } };
        const { getFieldDecorator } = this.props.form;
        let values = this.props.form.getFieldsValue();
        let time = values.time;
        let pagination = {
            showTotal: total => `共 ${total} 条数据`,
            pageSize: this.props.recinvoices.page.size,
            total: this.props.recinvoices.page.totalRow,
            showSizeChanger: true,
            current: this.props.recinvoices.page.page,
            onShowSizeChange: (current, size) => {
                let newPage = this.props.recinvoices.page;
                newPage.size = size;
                newPage.page = 1;
                this.props.dispatch({
                    type: 'recinvoices/getRecinvoicesList',
                    payload: {
                        contractno: values.contractno,
                        status: values.status,
                        page: newPage,
                    }
                });
            },
            onChange: (pageNumber, pageSize) => {
                let newPage = this.props.recinvoices.page;
                newPage.page = pageNumber;
                this.props.dispatch({
                    type: 'recinvoices/getRecinvoicesList',
                    payload: {
                        contractno: values.contractno,
                        status: values.status,
                        page: newPage,
                    }
                });
            }
        }

        return (
            <div>

                <Row>
                    <Col span={7}><FormItem {...formItemLayout} label={'合同协议号'}>{getFieldDecorator('contractno')(<Input placeholder="支持模糊搜索" />)}</FormItem></Col>
                    <Col span={7} style={{ float: 'left' }}>
                        <Button loading={this.props.loading} type="primary" icon="search" style={{ marginLeft: 35 }} onClick={this.handleSearch.bind(this)}>查询</Button>
                        <RightBox resource={RIGHT.DRAW.DRAW_INVOICE_BATCH_CHECKIN}> <Button loading={this.props.loading} type="primary" icon="search" style={{ marginLeft: 35 }} onClick={this.batchCheckinvoice.bind(this)}>批量认证发票</Button></RightBox>
                    </Col>
                </Row>

                <Row>
                    <Col span={7}>
                        <FormItem {...formItemLayout} label={'状态'}>
                            {getFieldDecorator('status', {
                                initialValue: '2'
                            })(
                                <RadioGroup style={{ width: 800 }}>
                                    <Radio value='2'>待收票</Radio>
                                    {/*                                         <Radio value='3'>待审核</Radio> */}
                                    <Radio value='4'>待验票</Radio>
                                    <Radio value='5'>已验票</Radio>
                                </RadioGroup>
                                )}
                        </FormItem>
                    </Col>

                </Row>
                <Table rowKey="id" loading={this.props.loading} dataSource={this.props.recinvoices.list} rowSelection={this.rowSelection} columns={this.columns} bordered={true} size={'middle'} pagination={pagination} scroll={{ x: 1200 }} />

                <InoviceDetail wrappedComponentRef={(inst) => this.inoviceDetail = inst} dispatch={this.props.dispatch}
                    handleSearch={this.handleSearch}
                    inoviceproductsList={this.props.recinvoices.inoviceproductsList}
                    invoices={this.props.recinvoices.inoviceheader}
                    drawerList={this.props.recinvoices.drawerList} />

            </div>
        )
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.recinvoices, recinvoices: state.recinvoices
    };
}

export default connect(mapStateToProps)(recinvoices);